package com.breeze.components.socket.redis.action;

import com.alibaba.fastjson2.JSONObject;
import com.breeze.components.socket.WebSocket;
import com.breeze.components.socket.WebSocketManager;
import com.breeze.components.socket.util.WebSocketUtil;
import java.util.Collection;

/**
 * 广播给所有的websocket发送消息action { "action":"broadcast", "message":"xxxxxxxxxxxxx" }
 *
 * @author breeze
 */
public class BroadCastAction implements Action {

  @Override
  public void doMessage(WebSocketManager manager, JSONObject object) {
    if (!object.containsKey(MESSAGE)) {
      return;
    }
    String message = object.getString(MESSAGE);
    // 从本地取出所有的websocket发送消息
    Collection<WebSocket> sockets = manager.localWebSocketMap().values();
    synchronized (sockets) {
      sockets.forEach(webSocket -> WebSocketUtil.sendMessage(webSocket.getSession(), message));
    }
  }
}
